package com.woniu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.entity.PageResult;
import com.woniu.entity.Result;
import com.woniu.pojo.Patrol;
import com.woniu.service.IPatrolServices;
import com.woniu.utils.PatrolPasswordSendSmsUtil;
import com.woniu.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/patrol")
@Api(tags = "巡检员管理")
@Slf4j
public class PatrolController extends BaseController{
    @Resource
    private IPatrolServices patrolServices;

    // 注入Redis模板
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //条件分页查
    @PostMapping("/search/{currentPage}/{pageSize}")
    @ApiOperation("条件分页搜索巡检员")
    public Result searchByPage(@RequestBody PatrolSearchVo patrolSearchVo,
                               @PathVariable Integer currentPage,
                               @PathVariable Integer pageSize){
        System.out.println(patrolSearchVo.getStreetId()+"拿到的街道id是这个呀");
        PageResult pageResult = patrolServices.searchByPage(currentPage,pageSize,patrolSearchVo);
        return toDataResult(pageResult);
    }
    //删除
    @DeleteMapping("/{id}")
    @ApiOperation("逻辑删除巡检员")
    public Result removeById(@PathVariable Long id){
        return toResult(patrolServices.removeByPatrolId(id));
    }
    //新增
    @PostMapping
    @ApiOperation("新增巡检员")
    public Result add(@RequestBody PatrolAddVo patrolAddVo){
        return toResult( patrolServices.add(patrolAddVo));
    }
    //根据id查
    @GetMapping("/{id}")
    @ApiOperation("根据巡检员id查巡检员")
    public Result searchById(@PathVariable Long id){
        return toDataResult(patrolServices.searchById(id));
    }
    //修改的方法
    @PutMapping
    @ApiOperation("编辑巡检员信息")
    public Result modify(@RequestBody PatrolAddVo patrolAddVo){
        return toResult(patrolServices.modify(patrolAddVo));
    }
    //禁用的方法
    @GetMapping("/stop/{id}")
    @ApiOperation("禁用巡检员")
    public Result stopPatrol(@PathVariable Long id){
        return toResult(patrolServices.stopPatrol(id));
    }
    //恢复的方法
    @GetMapping("/use/{id}")
    @ApiOperation("恢复巡检员")
    public Result usePatrol(@PathVariable Long id){
        return toResult(patrolServices.usePatrol(id));
    }
    //根据id查
    @GetMapping("/patrol/{id}")
    @ApiOperation("根据巡检员id查巡检员详细信息")
    public Result searchPatrolById(@PathVariable Long id){
        return toDataResult(patrolServices.searchPatrolById(id));
    }
    //查订单
    @GetMapping("/order/{id}")
    @ApiOperation("根据巡检员id去统计它操作的订单")
    public Result searchOrderById(@PathVariable Long id){
        return toDataResult(patrolServices.searchOrderById(id));
    }
    //查所有的订单
    @PostMapping("/orderList/{id}/{currentPage}/{pageSize}")
    @ApiOperation("订单的条件分页搜索")
    public Result searchAllOrderByPatrolId(@PathVariable Long id,
                                           @PathVariable Integer currentPage,
                                           @PathVariable Integer pageSize,
                                           @RequestBody OrderPatrolSearchVo orderPatrolSearchVo){
        return toDataResult(patrolServices.searchOrderListById(id,currentPage,pageSize,orderPatrolSearchVo));
    }
    //查考勤
    @GetMapping("/check/{id}/{currentPage}/{pageSize}")
    @ApiOperation("考勤的条件分页搜索")
    public Result searchCheckList(@PathVariable Long id,
                                  @PathVariable Integer currentPage,
                                  @PathVariable Integer pageSize) throws ParseException {
        return toDataResult(patrolServices.searchCheckList(id,currentPage,pageSize));
    }
    //查订单详情
    @GetMapping("/orderDetail/{id}")
    @ApiOperation("根据订单id查订单的详情")
    public Result searchOrderDetail(@PathVariable Long id){
        return toDataResult(patrolServices.searchOrderDetail(id));
    }
    //查收费模式
    @GetMapping("/chargeRule/{id}")
    @ApiOperation("通过路段id去查收费模式")
    public Result searchChargeRuleByRoadId(@PathVariable Long id){
        return toDataResult(patrolServices.searchChargeRuleByRoadId(id));
    }

    @ApiOperation("巡检员登录")
    @PostMapping("/login")
    public Result login(@RequestBody PatrolLoginVo loginVo) {
        //校验手机号正则表达式
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(16[5,6])|(17[0-8])|(18[0-9])|(19[1、5、8、9]))\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(loginVo.getPhone());
        boolean flag = matcher.matches();
        if(flag == false){
            return error("手机号格式错误！");
        }
        Patrol loginPatrol = patrolServices.login(loginVo);

        if (loginPatrol == null) {
            return error("手机号或密码错误");
        }

        return toDataResult(loginPatrol);
    }

    @ApiOperation("忘记密码,发送短信功能")
    @GetMapping("/sendSms/{phone}")
    public Result sendSmsCode(@PathVariable String phone) {
        //校验手机号正则表达式
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(16[5,6])|(17[0-8])|(18[0-9])|(19[1、5、8、9]))\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
        boolean flag = matcher.matches();
        if(flag == false){
            return error("手机号格式错误！");
        }
        // 1. 校验手机号码是否正确
        QueryWrapper<Patrol> phoneWrapper = new QueryWrapper<>();
        phoneWrapper.eq("phone", phone);
        Patrol sendTo = patrolServices.getOne(phoneWrapper);
        if (sendTo == null) {
            return error("手机号码不存在");
        }
        // 2. 手机号码存在 调用短信接口发送短信
        // 随机生成4位验证吗
        Random randObj = new Random();
        String code = Integer.toString(1000 + randObj.nextInt(9000));
        log.debug("======验证码为" + code + "======");
        // 将验证码保存到Redis中
        stringRedisTemplate.opsForValue().set("RESETCODE_" + phone, code, 60 * 5, TimeUnit.SECONDS);
        // 发送短信
        // PatrolPasswordSendSmsUtil smsUtil = new PatrolPasswordSendSmsUtil();
        // smsUtil.sendSms(phone, code);
        return success();
    }

    @ApiOperation("验证短信验证码")
    @GetMapping("/reset/{phone}/{code}")
    public Result checkCode(@PathVariable String phone, @PathVariable String code) {
        String redisCode = stringRedisTemplate.opsForValue().get("RESETCODE_" + phone);
        log.debug("======验证码为" + redisCode + "======");
        if (redisCode != null && redisCode.length() > 0) {
            if (redisCode.equals(code)) {
                log.debug("========短信验证成功=======");
                return success();
            }
        }
        return error("验证码错误");
    }

    @ApiOperation("重置密码")
    @PostMapping("/reset/password")
    public Result reset(@RequestBody PasswordResetVo resetVo) {
        // 空值检测
        if (resetVo.getPasswordFst() == null || resetVo.getPasswordFst().length() == 0) {
            return error("新密码不能为空");
        }
        if (resetVo.getPasswordSnd() == null || resetVo.getPasswordSnd().length() == 0) {
            return error("确认新密码不能为空");
        }


        // 确认两个密码相同
        if (resetVo.getPasswordFst().equals(resetVo.getPasswordSnd())) {
            // 根据电话查询账号
            QueryWrapper<Patrol> phoneWrapper = new QueryWrapper<>();
            phoneWrapper.eq("phone", resetVo.getPhone());
            Patrol resetPatrol = patrolServices.getOne(phoneWrapper);
            // 更新密码
            resetPatrol.setPassword(resetVo.getPasswordFst());
            boolean result = patrolServices.updateById(resetPatrol);
            return toResult(result);
        }
        return error();
    }
}
